import React, {useState, useEffect} from 'react'

import {inject, observer } from 'mobx-react'

// 
//没有必要被函数再次调用的代码，放到函数体外
const str = 'ct=24&qqmusic_ver=1298&new_json=1&remoteplace=txt.yqq.song&searchid=69692969799814090&t=0&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p=1&n=10&w=%E5%91%A8%E6%9D%B0&g_tk_new_20200303=1463344829&g_tk=1463344829&loginUin=3295849115&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0'
const params = {}
str.split('&').map(item => {
   const arr = item.split('=')
   params[arr[0]] = arr[1]
})
// console.log(params);

export default inject('searchMusic')(observer(props => {
  // console.log(props);
  //获取mobx注入的内容
  let {musicList, getMusicList, musicNum} = props.searchMusic
  // 开启一个定时器，属于副作用，需要使用useEffect
  // console.log(props); 
  //使用useState声明声明式变量
  const [count, setCount] = useState(0)
  //实现自增自减的操作
  const [num, setNum] = useState(0)
  //控制组件的元素/组件的显示或隐藏
  const [show, setShow] = useState(true)
  //操作音乐列表，用于网络请求数据
  // const [list, setList] = useState([]) //列表
  const [page, setPage] = useState(1)
  // const [limit, setLimit] = useState(10)
  const [singer, setSinger] = useState('')
  const [load, setLoad] = useState(0) //按下enter键的时候开始搜索，onChange的使用改变load的值，执行对应的useEffect()

  //定时器
  useEffect(() => {
    let time = null
    time = setInterval(() => {
      setCount(count + 1)
    }, 1000);
    // console.log(time);
    return () => {
      clearInterval(time)
    }

  }, [count])

  // 修改文章的标题：只修改一次，dom操作也属于副作用，需要使用useEffect
  useEffect(() => {
    document.title = 'hooks的使用';
    return () => undefined
  }, [])

  //请求音乐列表，网络请求也属于副作用，需要使用useEffect
  useEffect(() => {
    console.log(page);
    if(page <= 1) setPage(1)
    // if(!singer) return
    params.p = page
    params.w = singer
    //调用mobx中传递过来的方法，并传递参数回去
    getMusicList(params)
    // setSinger('')
    return () => undefined
  }, [page, load])

  // 渲染音乐列表
  const renderList = () => {
    return musicList && musicList.map(item => (
      <li key={item.id}>
        {item.album.title}
      </li>
    ))
  }

  //获取歌手
  const getSinger = (e) => {
    if(e.keyCode === 13) {
      setLoad(load + 1)
      setPage(1)
    }
  }
  return (
    <div>
      <h1>count: {count}</h1>
      <h1>num: {num}</h1>
      <button onClick={() => setNum(num + 10)}> + </button>
      <button onClick={() => setNum(num - 10)}> - </button>
      {show && <h1>使用hooks中的useState的API控制元素的显隐</h1>}
      <h1>是否显示：{show ? 'true' : 'false'}</h1>
      <button onClick={() => setShow(!show)}>显/隐</button>
      <h1>音乐列表</h1>
      <input type='text' value={singer} onChange={e => setSinger(e.target.value)} onKeyUp={getSinger} />
      <span>当前页歌曲数量：{musicNum}</span>
      <ul>
        {renderList()}
      </ul>
      <h2>当前页：{page}</h2>
      <button onClick={() => singer && setPage(page + 1)}>下一页</button>
      <button onClick={() =>singer && setPage(page - 1)}>上一页</button>
    </div>
  )
}))